<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="姓名" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="人员类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择人员类型" clearable size="small">
          <el-option
            v-for="dict in userTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" placeholder="请选择性别" clearable size="small">
          <el-option
            v-for="dict in sexOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人员状态" prop="userStatus">
        <el-select v-model="queryParams.userStatus" placeholder="请选择人员状态" clearable size="small">
          <el-option
            v-for="dict in userStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="请假状态" prop="sendStatus">
        <el-select v-model="queryParams.sendStatus" placeholder="请选择请假状态" clearable size="small">
          <el-option
            v-for="dict in sendStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['zhmk:person:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['zhmk:person:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['zhmk:person:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['zhmk:person:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="3">
        <el-select v-model="deviceIdList" placeholder="请选择设备" multiple clearable collapse-tags size="small">
          <el-option
            v-for="item in deviceList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
					:loading="exportLoading"
          @click="Issue"
        >下发</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
		<el-dialog title="下发结果" :visible.sync="dialogTableVisible" style="margin-top: 100px;">
		  <el-table :data="gridData">
		    <el-table-column property="zhmkDoorDevice.name" label="设备名称" align="center" ></el-table-column>
		    <el-table-column property="sendSuccessCount" label="下发成功数" align="center" ></el-table-column>
		    <el-table-column property="sendFailCount" label="下发失败数" align="center" ></el-table-column>
		  </el-table>
		</el-dialog>
    <el-table v-loading="loading" :data="personList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="人员ID" align="center" prop="id" /> -->
      <el-table-column label="姓名" align="center" prop="userName" />
      <el-table-column label="人员类型" align="center" prop="userType" :formatter="userTypeFormat" />
      <el-table-column label="联系电话" align="center" prop="phonenumber" />
      <el-table-column label="性别" align="center" prop="sex" :formatter="sexFormat" />
      <el-table-column label="年龄" align="center" prop="age" />
      <el-table-column label="人员状态" align="center" prop="userStatus" :formatter="userStatusFormat" />
      <!-- <el-table-column label="临时人员最后使用时间" align="center" prop="pwdUpdateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.pwdUpdateDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="下发状态" align="center" prop="sendStatus" :formatter="sendStatusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['zhmk:person:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['zhmk:person:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改人员信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="人员类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择人员类型">
            <el-option
              v-for="dict in userTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option
              v-for="dict in sexOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="人员状态" prop="userStatus">
          <el-select v-model="form.userStatus" placeholder="请选择人员状态">
            <el-option
              v-for="dict in userStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>   
        <el-form-item label="上传头像" prop="avatar">
          <!-- <el-input v-model="form.avatar" placeholder="请输入头像路径" /> -->
					<el-upload class="avatar-uploader" :action="uploadImgUrl" :show-file-list="false"
						:on-success="handleUploadSuccess" :headers="headers">
						<img v-if="imageUrl" :src="imageUrl" class="avatar">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
        </el-form-item>    
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
		
	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
<script>
import { listPerson, getPerson, delPerson, addPerson, updatePerson, exportPerson, personSend, findAll } from "@/api/zhmk/person";
import { getToken } from '@/utils/auth';
export default {
  name: "Person",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 人员信息表格数据
      personList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 人员类型字典
      userTypeOptions: [],
      // 性别字典
      sexOptions: [],
      // 人员状态字典
      userStatusOptions: [],
      // 请假状态字典
      sendStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        userType: null,
        phonenumber: null,
        sex: null,
        age: null,
        avatar: null,
        userStatus: null,
        pwdUpdateDate: null,
        sendStatus: null,
        deptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
      },
			imageUrl: '',
			// 图片上传配置
			uploadImgUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
			headers: {
				Authorization: 'Bearer ' + getToken()
			},
			imgurl: process.env.VUE_APP_BASE_IMG,
			deviceList: [],
			deviceIdList: [],
			dialogTableVisible: false,
			gridData: []
    };
  },
  created() {
    this.getList();		
		findAll().then(response => {
		  this.deviceList = response.data;
		  this.loading = false;
		});
    this.getDicts("person_type").then(response => {
      this.userTypeOptions = response.data;
    });
    this.getDicts("sys_user_sex").then(response => {
      this.sexOptions = response.data;
    });
    this.getDicts("person_user_type").then(response => {
      this.userStatusOptions = response.data;
    });
    this.getDicts("person_send_status").then(response => {
      this.sendStatusOptions = response.data;
    });
  },
  methods: {
    /** 查询人员信息列表 */
    getList() {
      this.loading = true;
      listPerson(this.queryParams).then(response => {
        this.personList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 人员类型字典翻译
    userTypeFormat(row, column) {
      return this.selectDictLabel(this.userTypeOptions, row.userType);
    },
    // 性别字典翻译
    sexFormat(row, column) {
      return this.selectDictLabel(this.sexOptions, row.sex);
    },
    // 人员状态字典翻译
    userStatusFormat(row, column) {
      return this.selectDictLabel(this.userStatusOptions, row.userStatus);
    },
    // 请假状态字典翻译
    sendStatusFormat(row, column) {
      return this.selectDictLabel(this.sendStatusOptions, row.sendStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
		// 上传成功
		handleUploadSuccess(res) {
			console.log(res.url)
			this.form.avatar = res.fileName;
			this.imageUrl = this.imgurl + res.fileName;
		},
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userName: null,
        userType: null,
        phonenumber: null,
        sex: null,
        age: null,
        avatar: null,
        userStatus: null,
        pwdUpdateDate: null,
        createTime: null,
        updateTime: null,
        sendStatus: null,
        deptId: null
      };
			this.imageUrl = '';
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加人员信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPerson(id).then(response => {
        this.form = response.data;
				this.imageUrl = process.env.VUE_APP_BASE_IMG + response.data.avatar;
        this.open = true;
        this.title = "修改人员信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePerson(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPerson(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除人员信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delPerson(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
		Issue() {
      const ids = this.ids;
			if(this.deviceIdList.length == 0 || ids.length == 0){
				this.$message({
					message: '下发需要选择下发设备和下发人员，请选择',
					type: 'success'
				});
			}else{
				this.$confirm('是否确认下发所选的数据项?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let that = this;
					personSend({
						"deviceIdList": this.deviceIdList,
						"personIdList": ids
					}).then(response => {
						that.dialogTableVisible = true;
						that.gridData = response.data;
						that.getList();
					});
				});
			}
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有人员信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportPerson(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
